/*
 *  Copyright 2013 National Institute of Advanced Industrial Science and Technology
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.sss.server;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.sss.common.SentinelThreadPool;
import org.sss.util.BlockPolicy;

public class WKThread extends Thread {
  @SuppressWarnings("unused")
  private static Logger logger = SssServer.getLogger(WKThread.class);
  private final int wkTID;
  public WKThread(Runnable r, int id, String threadName) {
    super(r, String.format("%s-%02d", threadName, id));
    this.wkTID = id;
  }
  public static WKThread currentThread() {
    return (WKThread) Thread.currentThread();
  }
  public int getIOTID() {
    return wkTID;
  }

  public static SentinelThreadPool createPool(SssServerConfiguration sssConf, String threadName) {
    return new SentinelThreadPool(
        sssConf.wk_threads_max, sssConf.wk_threads_max,
        0L, TimeUnit.MILLISECONDS,
        new LinkedBlockingQueue<Runnable>(sssConf.wktp_workqueue_limit),
        new Factory(threadName),
        new BlockPolicy());
  }

  private static class Factory implements ThreadFactory {
    private final String threadName;
    private final AtomicInteger counter = new AtomicInteger();

    public Factory(String threadName) {
      this.threadName = threadName;
    }
    @Override
    public Thread newThread(Runnable r) {
      return new WKThread(r, newId(), threadName);
    }
    private int newId() {
      return counter.getAndIncrement();
    }
  }
}
